#include "s-int.h"


#ifdef _DEBUG

using namespace std;

ofstream fs;
CRITICAL_SECTION cs;

void CreateLogger(const wchar_t* fileName)
{
	// Initialize the critical section one time only.
	InitializeCriticalSectionAndSpinCount(&cs, 0x80000400);

	fs.open(fileName, ios::in | ios::out | ios::trunc);
}

void CloseLogger()
{
	fs.close();

    // Release resources used by the critical section object.
    DeleteCriticalSection(&cs);
}

void WriteLogger(const char* lpszText, ...)
{
	char buffer[MAX_CHAR];

	va_list ap;
	va_start(ap, lpszText);
	vsprintf(buffer, lpszText, ap);
	va_end(ap);

	// Request ownership of the critical section.
	EnterCriticalSection(&cs); 

	fs << buffer << endl;
	fs.flush();

	// Release ownership of the critical section.
	LeaveCriticalSection(&cs);
}


inline char Hex2Asic(const char x)
{
	if(x >= 0xA && x <= 0xF)
		return x + 'A' - 10;
	else
		return x + '0';
}
inline char* GetHex(const char x, char* buf)
{
	char* p = buf;
	*p++ = Hex2Asic((x >> 4) & 0xF);
	*p++ = Hex2Asic(x & 0xF);
	return buf;
}

void WritePackage(SENDRECIEVE how, PACKAGESTATE state, unsigned int s, const char* buf, int len)
{
	char hex[3] = {0};

	switch(how)
	{
	case SENDRECIEVE::RECIEVE:
		fs << "Receive package"; break;
	case SENDRECIEVE::SEND:
		fs << "Send package"; break;
	}

	switch(state)
	{
	case PACKAGESTATE::ORIGINAL:
		fs << " [ORIGINAL]"; break;
	case PACKAGESTATE::ENCRYPED:
		fs << " [ENCRYPED]"; break;
	}


	// Request ownership of the critical section.
	EnterCriticalSection(&cs); 


	fs << " SOCKET=" << s << " len=" << len << " BYTE=";
	while(len-->0)
	{
		fs << " " << GetHex(*buf++, hex);
	}
	fs << endl;
	fs.flush();


	// Release ownership of the critical section.
	LeaveCriticalSection(&cs);
}

#endif //__509_DEBUG
